package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"aiserver/pkg/config"
	"aiserver/pkg/router"

	"gitee.com/wujianqiang/golibs/pkg/logging"
	"github.com/urfave/cli/v2"
)

func main() {

	app := &cli.App{
		Name:        "aiserver",
		Usage:       "aiserver for ai  system",
		Description: "aiserver for ai  system",
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:        "config",
				Usage:       "Configuration file",
				DefaultText: "config.yaml",
				Value:       "config.yaml",
			},
		},
		Action:  startServer,
		Version: "1.0.0",
	}
	err := app.Run(os.Args)
	log := logging.GetLogger()
	if err != nil {
		log.Fatalln(err)
	}
}

// func initserver(c *cli.Context) error {
// 	err := config.PrepareServer(c.String("config"))
// 	if err != nil {
// 		return err
// 	}

// 	defer config.Appconfig.RDS.Close()

// 	return nil

// }
func startServer(c *cli.Context) error {
	err := config.PrepareServer(c.String("config"))
	if err != nil {
		return err
	}

	defer config.Appconfig.RDS.Close()
	log := logging.GetLogger()
	routers := router.Router()
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

	go func() {
		sig := <-sigChan
		log.Infoln("exit requested, shutting down", "signal", sig)
		_ = routers.Shutdown()
		log.Exit(1)
	}()

	return routers.Listen(fmt.Sprintf(":%d", config.Appconfig.Server.Port))
}
